const { pool } = require('./database');
const bcrypt = require('bcryptjs');

class UserModel {
  // 创建新用户
  static async createUser(username, password, email) {
    try {
      // 密码加密
      const hashedPassword = await bcrypt.hash(password, 10);
      
      const [result] = await pool.query(
        'INSERT INTO users (username, password, email) VALUES (?, ?, ?)',
        [username, hashedPassword, email]
      );
      
      return result.insertId;
    } catch (error) {
      console.error('创建用户失败:', error);
      throw error;
    }
  }

  // 通过用户名查找用户
  static async findByUsername(username) {
    try {
      const [rows] = await pool.query(
        'SELECT * FROM users WHERE username = ?',
        [username]
      );
      return rows[0];
    } catch (error) {
      console.error('查找用户失败:', error);
      throw error;
    }
  }

  // 验证用户密码
  static async validatePassword(plainPassword, hashedPassword) {
    return await bcrypt.compare(plainPassword, hashedPassword);
  }

  // 更新用户信息
  static async updateUser(userId, updateData) {
    try {
      const [result] = await pool.query(
        'UPDATE users SET ? WHERE id = ?',
        [updateData, userId]
      );
      return result.affectedRows > 0;
    } catch (error) {
      console.error('更新用户失败:', error);
      throw error;
    }
  }

  // 删除用户
  static async deleteUser(userId) {
    try {
      const [result] = await pool.query(
        'DELETE FROM users WHERE id = ?',
        [userId]
      );
      return result.affectedRows > 0;
    } catch (error) {
      console.error('删除用户失败:', error);
      throw error;
    }
  }
}

module.exports = UserModel; 